package com.kqzz.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * 
 * Title: TDLZBASE<br>
 * Description: 网络工具类<br>
 * Copyright: Copyright (c) 2016 <br>
 * Create DateTime: 2016-5-25 下午4:28:25 <br>
 * CVS last modify person: fuxiaorong-len <br>
 * CVS last modify DateTime: 2016-5-25 <br>
 * 
 * @author fuxiaorong-len
 */
public class NetworkUtil {

	public static String LOCALIPADDRESS_1 = "127.0.0.1";
	public static String LOCALIPADDRESS_2 = "0:0:0:0:0:0:0:1";

	/**
	 * 获取客户端的ip地址
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = null;
		ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (LOCALIPADDRESS_1.equals(ip) || LOCALIPADDRESS_2.equals(ip)) {
			// 通过request获取的本地ip地址需要转换成为实际的ip地址
			try {
				// 获取本地实际的ip地址
				ip = InetAddress.getLocalHost().getHostAddress();
			} catch (java.net.UnknownHostException e) {
				e.printStackTrace();
			}
		}
		return ip;
	}

}
